package com.bang.study.esl.runner;

import com.bang.study.esl.model.EslClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Timer;
import java.util.TimerTask;


@Slf4j
@Component
public class EslInboundServer implements ApplicationRunner {

    private Timer timer = new Timer();

    @Override
    public void run(ApplicationArguments args) {
        //10s后检测ESL连接状态
        testEslConnStatus();
        //连接FS
        EslClient.getInstance();
        EslClient.addEventListener();
        EslClient.setEventSubscriptions();
    }

    /**
     * 检测ESL连接状态
     */
    public void testEslConnStatus() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                if (!EslClient.canSend()) {
                    printEslConnErrMsg();
                }
            }
        }, 10000);
    }

    /**
     * 打印FS连接异常信息
     */
    private void printEslConnErrMsg() {
        log.error("->");
        log.error("->");
        log.error("->");
        log.error("->");
        log.error("->");
        log.error("[ERR]->ESL连接异常,原因可以如下:");
        log.error("[ERR]->1. FreeSwitch未启动.");
        log.error("[ERR]->2. ESL连接信息不正确.");
        log.error("[ERR]->3. Freeswitch不允许外部连接,查看event_socket.conf.xml配置.");
        log.error("<-");
        log.error("<-");
        log.error("<-");
        log.error("<-");
        log.error("<-");
        System.exit(-1);
    }
}